﻿using System;

namespace Murry.DataStore
{
    /// <summary>
    /// Base class for read/write DataStores
    /// </summary>
    /// <typeparam name="TInternalDatabase">Internal Database Type.</typeparam>
    public abstract class DataStore<TInternalDatabase> : ReadOnlyDataStore<TInternalDatabase>, IDataStore
    {
        /// <summary>
        /// Create a new object that implements the given interface.
        /// </summary>
        /// <typeparam name="TInterface">Interface type</typeparam>
        /// <returns>New entity.</returns>
        /// <exception cref="ArgumentException">If TInterface is not supported or id not found.</exception>
        /// <exception cref="InvalidOperationException">If the associated implementation object cannot be constructed.</exception>
        public virtual TInterface Create<TInterface>()
            where TInterface : IPersist
        {
            var implementedType = Entities.GetImplementedEntityType(GetType(), typeof(TInterface));

            var ctor = implementedType.GetConstructor(new[] { typeof(TInternalDatabase) });

            if (ctor == null)
            {
                throw new InvalidOperationException(string.Format("Type {0} does not have the proper constructor.", implementedType.FullName));
            }

            return (TInterface)ctor.Invoke(new object[] { Database });
        }
    }
}
